<?php
    namespace app\controllers;
    use app\common\BaseController;
    use app\common\Utils;
    use app\models\Emotion;

    class EmotionController extends BaseController{
        public function actionAdd(){
            $postData = \Yii::$app->request->post();
            $emotion = new Emotion();
            if (isset($postData['id']) && !empty($postData['id'])){
                $emotion = Emotion::find()->where(['id' => $postData['id']])->one();
            }
            $postData['time'] = strtotime($postData['time']);
            foreach ($postData as $key => $value){
                if ($key !== 'time'){
                    $postData[$key] = Utils::encode($value);
                }
            }
            if ($emotion->load($postData, '') && $emotion->save()){
                $res = 0;
            }else{
                $res = $emotion->errors;
            }
            return $this->result([], $res);
        }

        public function actionList(){
            $rawRes = Emotion::find()->asArray()->all();
            foreach ($rawRes as $key => $value){
                foreach ($value as $innerKey => $innerVal){
                    if ($innerKey !== 'id' && $innerKey !== 'time'){
                        $rawRes[$key][$innerKey] = Utils::decode($innerVal);
                    }
                }
                $rawRes[$key]['time'] = date('Y-m-d H:i:s', $rawRes[$key]['time']);
            }
            return $this->result($rawRes, 0);
        }

        public function actionGetEmotionById(){
            $id = \Yii::$app->request->get('id', 0);
            $emotion = [];
            if ($id){
                $emotion = Emotion::find()->where(['id' => $id])->asArray()->one();
                foreach ($emotion as $key => $val){
                    if ($key !== 'id' && $key !== 'time'){
                        $emotion[$key] = Utils::decode($val);
                    }
                }
                $emotion['time'] = date('Y-m-d H:i:s', $emotion['time']);
            }
            return $this->result($emotion);
        }
    }